package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssm.sport.entity.Product;
import com.ssm.sport.mapper.ProductMapper;
import com.ssm.sport.service.ProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 商品服务实现类
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Override
    public IPage<Product> searchProducts(String keyword, Page<Product> page) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只查询上架商品

        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.and(wrapper ->
                    wrapper.like("name", keyword)
                            .or()
                            .like("subtitle", keyword)
            );
        }

        queryWrapper.orderByDesc("create_time");

        Page<Product> productPage = baseMapper.selectPage(page, queryWrapper);
        if (productPage.getRecords() != null) {
            productPage.getRecords().forEach(product -> {
                product.setMainImage("/sport_mall_war" + product.getMainImage());
            });
        }
        return productPage;
    }

    @Override
    public List<Product> getHotProducts(int limit) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询上架商品
                .eq("is_hot", 1)  // 查询热门商品
                .orderByDesc("sold_count")
                .last("LIMIT " + limit);

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<Product> getNewProducts(int limit) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询上架商品
                .eq("is_new", 1)  // 查询新品
                .orderByDesc("create_time")
                .last("LIMIT " + limit);

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<Product> getProductsByCategory(Integer categoryId, Page<Product> page, String sort) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                .eq("status", 1); // 只查询上架商品

        // 添加排序
        if (sort != null) {
            switch (sort) {
                case "price-asc":
                    queryWrapper.orderByAsc("price");
                    break;
                case "price-desc":
                    queryWrapper.orderByDesc("price");
                    break;
                case "sales":
                    queryWrapper.orderByDesc("sales");
                    break;
                default:
                    queryWrapper.orderByDesc("create_time"); // 默认按照创建时间排序
                    break;
            }
        } else {
            queryWrapper.orderByDesc("create_time"); // 默认按照创建时间排序
        }

        Page<Product> productPage = baseMapper.selectPage(page, queryWrapper);
        if (productPage.getTotal() > 0) {
            productPage.getRecords().forEach(product -> {
                product.setMainImage("/sport_mall_war" + product.getMainImage());
            });
        }
        return productPage;
    }

    @Override
    public List<Product> getRelatedProducts(Integer productId, Integer categoryId, int limit) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1) // 只查询上架商品
                .eq("category_id", categoryId) // 同分类商品
                .ne("id", productId) // 不包含当前商品
                .orderByDesc("sold_count") // 按销量降序
                .last("LIMIT " + limit);

        List<Product> relatedProducts = baseMapper.selectList(queryWrapper);

        // 如果相关商品不足，则补充一些热门商品
        if (relatedProducts.size() < limit) {
            int remainingCount = limit - relatedProducts.size();

            QueryWrapper<Product> hotQueryWrapper = new QueryWrapper<>();
            hotQueryWrapper.eq("status", 1) // 只查询上架商品
                    .eq("is_hot", 1) // 热门商品
                    .ne("id", productId) // 不包含当前商品
                    .notIn(relatedProducts.size() > 0, "id",
                            relatedProducts.stream().map(Product::getId).toArray()) // 排除已有的相关商品
                    .orderByDesc("sold_count")
                    .last("LIMIT " + remainingCount);

            List<Product> hotProducts = baseMapper.selectList(hotQueryWrapper);
            relatedProducts.addAll(hotProducts);
        }

        return relatedProducts;
    }

    @Override
    public IPage<Product> getProductsByCategory(Integer categoryId, Page<Product> page) {
        return getProductsByCategory(categoryId, page, null);
    }

    @Override
    public Long getTotalStock() {
        // 查询所有商品
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1); // 只统计上架商品的库存
        List<Product> products = baseMapper.selectList(queryWrapper);
        
        // 计算总库存
        return products.stream()
                .mapToLong(product -> product.getStock() != null ? product.getStock() : 0L)
                .sum();
    }
} 